import { login } from '@/api/common'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { emptyCacheAction } from '@/api/common'
import { mapTreeModules } from '@/utils'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    company_id: '',
    btnPermission: [],
    menuPermission: [],
    userId: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_COMPANY: (state, payload) => {
    state.company_id = payload
  },
  SET_PERMISSION: (state, payload) => {
    state.btnPermission = payload.btnPermission
    state.menuPermission = payload.menuPermission
  },
  SET_USER_ID: (state, payload) => {
    state.userId = payload
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { name, company_id, token } = response.data
        commit('SET_TOKEN', token)
        commit('SET_NAME', name)
        commit('SET_COMPANY', company_id)

        dispatch('tagsView/delAllViews', {}, { root: true })
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // getUserInfo().then(response => {
      const { name, company_id, id } = { name: '1', company_id: 1, id: 1 }
      const menuPermission = mapTreeModules()
      commit('SET_PERMISSION', { btnPermission: [], menuPermission })

      const roles = ['admin']
      commit('SET_ROLES', roles)
      commit('SET_NAME', name)
      commit('SET_COMPANY', company_id)
      commit('SET_USER_ID', id)

      resolve({ roles, menuPermission })
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      emptyCacheAction()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

